

#include "ChannelManager.h"

ChannelManager *ChannelManager::_pInstance = nullptr;

ChannelManager *ChannelManager::Instance() {
  if (!_pInstance) {
    _pInstance = new ChannelManager();
  }
  return _pInstance;
}

void ChannelManager::Destroy() {
  DELETE_PTR(_pInstance);
}

ChannelManager::~ChannelManager() {
  UniqueLock uniqueLock(_Event.getMutex());
  _Event.lock(uniqueLock);
  std::for_each(_ChannelList.begin(), _ChannelList.end(), [&](IChannel *pTmpChannel) {
    DELETE_PTR(pTmpChannel)
  });
  _ChannelList.clear();
  _Event.unlock(uniqueLock);
}

IChannel *ChannelManager::createChannel(ChannelType channelType) {
  return Channel_Create(channelType);
}

void ChannelManager::destroyChannel(IChannel *pChannel) {
  Channel_Destroy(pChannel);
}

IChannel *ChannelManager::findChannel(ChannelType channelType) {
  IChannel *pChannel = nullptr;
  UniqueLock uniqueLock(_Event.getMutex());
  _Event.lock(uniqueLock);
  std::for_each(_ChannelList.begin(), _ChannelList.end(), [&](IChannel *pTmpChannel) {
    if (pTmpChannel && pTmpChannel->getChannelType() == channelType) {
      pChannel = pTmpChannel;
    }
  });
  _Event.unlock(uniqueLock);
  return pChannel;
}

bool ChannelManager::bindCapture(ChannelType channelType, ICapture *pCapture) {
  IChannel *pChannel = findChannel(channelType);
  if (pChannel) {
    pChannel->bindCapture(pCapture);
  }

  return false;
}

void ChannelManager::unbindCapture(ChannelType channelType, ICapture *pCapture) {
  IChannel *pChannel = findChannel(channelType);
  if (pChannel) {
    pChannel->unbindCapture(pCapture);
  }
}

bool ChannelManager::bindRender(ChannelType channelType, IRender *pRender) {
  IChannel *pChannel = findChannel(channelType);
  if (pChannel) {
    pChannel->bindRender(pRender);
  }
}

void ChannelManager::unbindRender(ChannelType channelType, IRender *pRender) {
  IChannel *pChannel = findChannel(channelType);
  if (pChannel) {
    pChannel->unbindRender(pRender);
  }
}